package com.amigo.online.provider.user.config;

import java.net.UnknownHostException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import com.mongodb.MongoClientURI;

@Configuration
public class MongoConfig {

    @Value("${spring.data.mongodb.read.uri}")
    private String mongoReadUri;

    @Value("${spring.data.mongodb.write.uri}")
    private String mongoWriteUri;

    @Bean
    public MongoMappingContext mongoMappingContext() {
        MongoMappingContext mappingContext = new MongoMappingContext();
        return mappingContext;
    }

    // ==================== 连接到 mongodb user 服务器

    /*
     * @Bean //使用自定义的typeMapper去除写入mongodb时的“_class”字段 public MappingMongoConverter
     * mappingMongoConverter1() throws Exception { DefaultDbRefResolver
     * dbRefResolver = new DefaultDbRefResolver(this.dbFactory1());
     * MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver,
     * this.mongoMappingContext()); converter.setTypeMapper(new
     * DefaultMongoTypeMapper(null)); return converter; }
     */

    @Bean
    @Primary
    public MongoDbFactory dbReadFactory() throws UnknownHostException {
        return new SimpleMongoDbFactory(new MongoClientURI(mongoReadUri));
    }

    // ==================== 连接到 mongodb video 服务器
    @Bean("readMongoTemplate")
    @Primary
    public MongoTemplate readMongoTemplate() throws Exception {
        return new MongoTemplate(this.dbReadFactory());
    }

    @Bean
    public MongoDbFactory dbWriteFactory() throws UnknownHostException {
        return new SimpleMongoDbFactory(new MongoClientURI(mongoWriteUri));
    }

    @Bean("writeMongoTemplate")
    public MongoTemplate writeMongoTemplate() throws Exception {
        return new MongoTemplate(dbWriteFactory());
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(dbWriteFactory());
    }
}
